﻿namespace UglyToad.PdfPig.DocumentLayoutAnalysis.PageSegmenter
{
    using Content;
    using Core;
    using System;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// Default Page Segmenter. All words are included in one block.
    /// </summary>
    public class DefaultPageSegmenter : IPageSegmenter
    {
        private readonly DefaultPageSegmenterOptions options;

        /// <summary>
        /// Create an instance of default page segmenter, <see cref="DefaultPageSegmenter"/>.
        /// </summary>
        public static DefaultPageSegmenter Instance { get; } = new DefaultPageSegmenter();

        /// <summary>
        /// using default options values.
        /// </summary>
        public DefaultPageSegmenter() : this(new DefaultPageSegmenterOptions())
        {
        }

        /// <summary>
        /// Create using options values.
        /// </summary>
        /// <param name="options">The <see cref="DefaultPageSegmenterOptions"/> to use.</param>
        /// <exception cref="ArgumentNullException"></exception>
        public DefaultPageSegmenter(DefaultPageSegmenterOptions options)
        {
            this.options = options ?? throw new ArgumentNullException(nameof(options));
        }

        /// <summary>
        /// Get the text blocks using options.
        /// </summary>
        /// <param name="words">The page's words to generate text blocks for.</param>
        /// <returns>The <see cref="TextBlock"/>s generated by the default method.</returns>
        public IReadOnlyList<TextBlock> GetBlocks(IEnumerable<Word> words)
        {
            if (words?.Any() != true)
            {
                return Array.Empty<TextBlock>();
            }

            return new List<TextBlock>() { new TextBlock(new XYLeaf(words).GetLines(options.WordSeparator), options.LineSeparator) };
        }

        /// <summary>
        /// Default page segmenter options.
        /// </summary>
        public class DefaultPageSegmenterOptions : IPageSegmenterOptions
        {
            /// <summary>
            /// <inheritdoc/>
            /// Default value is -1.
            /// </summary>
            public int MaxDegreeOfParallelism { get; set; } = -1;

            /// <summary>
            /// <inheritdoc/>
            /// <para>Default value is ' ' (space).</para>
            /// </summary>
            public string WordSeparator { get; set; } = " ";

            /// <summary>
            /// <inheritdoc/>
            /// <para>Default value is '\n' (new line).</para>
            /// </summary>
            public string LineSeparator { get; set; } = "\n";
        }
    }
}